const PAGE_SIZE_TYPES = {
  SIZE_POS: 'SIZE_POS',
  UPDATE_GETTER_FLAG: 'UPDATE_GETTER_FLAG',
  CLEAR_SEARCH_PAGE_SIZE: 'CLEAR_SEARCH_PAGE_SIZE'
};

const state = {
  sizePos: {},
  updateGetterFlag: null
};
const getters = {
  getMenuSizePos: (state) => (userId, menuId) => {
    console.log('Should update getter?', state.updateGetterFlag);
    if (state.updateGetterFlag) {
      const updatedRecordSearch = getters.getMenuSizePos(userId, menuId);
      return updatedRecordSearch;
    } else {
      return state.sizePos?.[userId]?.[menuId] || {};
    }
  },
};

const mutations = {
  [PAGE_SIZE_TYPES.SIZE_POS] (state, { userId, menuId, sizePos = {} }) {
    if (!state.sizePos[userId]) {
      state.sizePos[userId] = {};
    }
    state.sizePos[userId][menuId] = sizePos;
  },
  // 新增的mutation，用于标记需要重新计算getter
  [PAGE_SIZE_TYPES.UPDATE_GETTER_FLAG] (state, flag) {
    state.updateGetterFlag = flag;
  },
  [PAGE_SIZE_TYPES.CLEAR_SEARCH_PAGE_SIZE] (state, userId) {
    if (state.sizePos[userId]) {
      state.sizePos[userId] = {};
    }
  }
};

const actions = {
  async recordSearchPageSize ({ commit }, options) {
    const { userId, menuId, page, size } = options
    // 更新updateGetterFlag为true，表示需要重新计算getter
    commit(PAGE_SIZE_TYPES.UPDATE_GETTER_FLAG, true);
    commit(PAGE_SIZE_TYPES.SIZE_POS, { userId, menuId, sizePos: { page, size } });
    commit(PAGE_SIZE_TYPES.UPDATE_GETTER_FLAG, false);
  },
  async clearSearchPageSize ({ commit }, userId) {
    commit(PAGE_SIZE_TYPES.CLEAR_SEARCH_PAGE_SIZE, userId);
    commit(PAGE_SIZE_TYPES.UPDATE_GETTER_FLAG, false);
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};